package com.zhangmeng.tools.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.zhangmeng.tools.date.ResultDate;
import com.zhangmeng.tools.utils.JsoupUtil;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.chrono.Chronology;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.*;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-03-04 16:48
 */
@Slf4j
public class DateController {

    @FXML
    private DatePicker datePicker;

    private List<Map<String,Object>> list = FXCollections.observableArrayList();

    private DateSimpler dateSimpler = new DateSimpler();

    private static RestTemplate restTemplate;

    public static Map<String,DateSimpler>  map = new HashMap<>();

    @FXML
    private TextField animal;

    @FXML
    private TextField chinese_calendar;

    @FXML
    private TextField solar_calendar;

    @FXML
    private TextArea suit;

    @FXML
    private TextArea avoid;

    @FXML
    private TextField term;

    @FXML
    private TextField value;

    public static String post_query(String url,Map<String,String> params){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if(param.length()>0){
                        param.append("&");
                    }
                    param.append(entry.getKey());
                    param.append("=");
                    param.append(entry.getValue());
                    //System.out.println(entry.getKey()+":"+entry.getValue());
                }
                //System.out.println("param:"+param.toString());
                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    public static void getData(String date) {
        String url = "https://opendata.baidu.com/api.php";
        if (restTemplate == null){
            restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        }
        Map<String, String> formData = new HashMap<>();
        formData.put("tn", "wisetpl");
        formData.put("format", "json");
        formData.put("resource_id", "39043");
        formData.put("query", date);
        formData.put("t", String.valueOf(new Date().getTime()));

        String json = post_query(url, formData);
        ResultDate resultDate = JSON.parseObject(json,ResultDate.class);

        if (resultDate != null){
            map.clear();
            List<ResultDate.DataBean> data = resultDate.getData();
            for (ResultDate.DataBean datum : data) {
                List<ResultDate.DataBean.AlmanacBean> almanac = datum.getAlmanac();
                for (ResultDate.DataBean.AlmanacBean almanacBean : almanac) {
                    String year = almanacBean.getYear();
                    String month = almanacBean.getMonth();
                    String day = almanacBean.getDay();
                    DateSimpler da = new DateSimpler();
                    da.setAnimal(almanacBean.getAnimal());
                    da.setAvoid(almanacBean.getAvoid());
                    da.setSuit(almanacBean.getSuit());
                    String oDate = year + "-" + month  + "-" + day;
                    da.setChinese_calendar(oDate);
                    da.setSolar_calendar(almanacBean.getGzYear() + "年" + almanacBean.getGzMonth() + "月" + almanacBean.getGzDate() + "日");
                    da.setTerm(almanacBean.getTerm());
                    da.setValue(almanacBean.getValue());
                    log.info("date:{}",oDate);
                    map.put(oDate,da);
                }
            }
        }
    }

    public static String charset_for_gbk(String content){
        return new String(content.getBytes(StandardCharsets.UTF_8),Charset.forName("GBK"));
    }

    public  void set_value(DateSimpler dateSimpler){
        if (dateSimpler != null){
            animal.setText(dateSimpler.getAnimal());
            suit.setText(dateSimpler.getSuit());
            avoid.setText(dateSimpler.getAvoid());
            solar_calendar.setText(dateSimpler.getSolar_calendar());
            chinese_calendar.setText(dateSimpler.getChinese_calendar());
            term.setText(dateSimpler.getTerm());
            value.setText(dateSimpler.getValue());
        }
    }

    @FXML
    public void initialize() {

        suit.setWrapText(true);
        avoid.setWrapText(true);

        LocalDate now = LocalDate.now();
        int y = now.getYear();
        int d = now.getDayOfMonth();
        int m = now.getMonth().getValue();
        String date_string = String.format("%d年%d月", y, m);
        getData(date_string);
        String query = y + "-" + m  + "-" + d;
        DateSimpler dateSimpler = map.get(query);
        set_value(dateSimpler);

        datePicker.setValue(now);
        datePicker.setPrefWidth(210);
        datePicker.setEditable(true);

        datePicker.setOnAction(event -> {
            LocalDate value = datePicker.getValue();
            int year = value.getYear();
            int month = value.getMonthValue();
            int day = value.getDayOfMonth();
            String qo = year + "-" + month + "-" + day;
            DateSimpler dateSimpler1 = map.get(qo);
            if (dateSimpler1 == null){
                getData(year + "年" + month + "月");
                dateSimpler1 = map.get(qo);
                set_value(dateSimpler1);
            }else {
                set_value(dateSimpler1);
            }
        });
        datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            int year = newValue.getYear();
            int month = newValue.getMonthValue();
            int day = newValue.getDayOfMonth();
            int week = newValue.getDayOfWeek().getValue();
            int dayOfYear = newValue.getDayOfYear();
            log.info(year + "年" + month + "月" + day + "日" + "星期" + week + "一年中的第" + dayOfYear + "天");
        });

        datePicker.setDayCellFactory(new Callback<>() {
            @Override
            public DateCell call(DatePicker param) {
                return new DateCell() {
                    @Override
                    public void updateItem(LocalDate item, boolean empty) {
                        super.updateItem(item, empty);
                        this.setText(item.toString());
                    }
                };
            }
        });
    }

    public static class DateSimpler{

        private final SimpleStringProperty chinese_calendar = new SimpleStringProperty(this, "chinese_calendar");//农历
        private final SimpleStringProperty solar_calendar = new SimpleStringProperty(this, "solar_calendar");//阳历
        private final SimpleStringProperty suit = new SimpleStringProperty(this, "suit");//宜
        private final SimpleStringProperty avoid = new SimpleStringProperty(this, "avoid");//忌
        private final SimpleStringProperty animal = new SimpleStringProperty(this, "animal");//属相
        private final SimpleStringProperty term = new SimpleStringProperty(this, "term");//节气
        private final SimpleStringProperty value = new SimpleStringProperty(this, "value");//纪念日

        public String getTerm() {
            return term.get();
        }

        public SimpleStringProperty termProperty() {
            return term;
        }

        public void setTerm(String term) {
            this.term.set(term);
        }

        public String getValue() {
            return value.get();
        }

        public SimpleStringProperty valueProperty() {
            return value;
        }

        public void setValue(String value) {
            this.value.set(value);
        }

        public String getSuit() {
            return suit.get();
        }

        public SimpleStringProperty suitProperty() {
            return suit;
        }

        public void setSuit(String suit) {
            this.suit.set(suit);
        }

        public String getAvoid() {
            return avoid.get();
        }

        public SimpleStringProperty avoidProperty() {
            return avoid;
        }

        public void setAvoid(String avoid) {
            this.avoid.set(avoid);
        }

        public String getAnimal() {
            return animal.get();
        }

        public SimpleStringProperty animalProperty() {
            return animal;
        }

        public void setAnimal(String animal) {
            this.animal.set(animal);
        }

        public String getChinese_calendar() {
            return chinese_calendar.get();
        }

        public SimpleStringProperty chinese_calendarProperty() {
            return chinese_calendar;
        }

        public void setChinese_calendar(String chinese_calendar) {
            this.chinese_calendar.set(chinese_calendar);
        }

        public String getSolar_calendar() {
            return solar_calendar.get();
        }

        public SimpleStringProperty solar_calendarProperty() {
            return solar_calendar;
        }

        public void setSolar_calendar(String solar_calendar) {
            this.solar_calendar.set(solar_calendar);
        }
    }
}
